package com.cxb.utils;

import java.io.File;
import java.io.IOException;

import android.content.Context;
import android.content.Intent;

import com.amitek.aidl.mqtt.bean.OtaStatus;

public class UpdateUtils {

	public static final String EXTRA_VERSION = "version";
	public static final String EXTRA_UPDATEINFO = "updateInfo";
	public static final String EXTRA_DOWNLOAD_URL = "downloadUrl";
	public static final String EXTRA_FILE_MD5 = "fileMd5";
	public static final String EXTRA_FILE_SIZE = "fileSize";
	public static final String EXTRA_FORCE_UPDATE = "forceUpdate";
	public static final String EXTRA_UPDATE_PACKAGE_PATH = "updatePackagePath";

	public static final String ACTION_OTA_UPDATE = "ACTION_OTA_UPDATE";
	public static final String ACTION_UPDATE_FROM_SDCARD = "ACTION_UPDATE_FROM_SDCARD";

	public static final String SDCARD_UPDATE_PACKAGE_NAME = "ami_update.zip";

	public static void startUpdate(Context context, OtaStatus otaInfo) {
		if (CommonUtils.getSystemProperties("cxb.software.version").equals(
				otaInfo.version)) {
			return;
		}
		Intent updateIntent = new Intent(ACTION_OTA_UPDATE);
		updateIntent.setClassName("com.amitek.ota",
				"com.amitek.ota.service.OTAService");
		updateIntent.putExtra(EXTRA_VERSION, otaInfo.version);
		updateIntent.putExtra(EXTRA_UPDATEINFO, otaInfo.updateInfo);
		updateIntent.putExtra(EXTRA_DOWNLOAD_URL, otaInfo.downloadUrl);
		updateIntent.putExtra(EXTRA_FILE_MD5, otaInfo.fileMd5);
		updateIntent.putExtra(EXTRA_FILE_SIZE, otaInfo.fileSize);
		updateIntent.putExtra(EXTRA_FORCE_UPDATE, otaInfo.forceUpdate);

		context.startService(updateIntent);
	}

	public static void updateFromSdCard(Context context) {

		if (!isSDUpdatePackageExist()) {
			return;
		}
		Intent updateIntent = new Intent(ACTION_UPDATE_FROM_SDCARD);
		updateIntent.setClassName("com.amitek.ota",
				"com.amitek.ota.service.OTAService");
		updateIntent.putExtra(EXTRA_UPDATE_PACKAGE_PATH, "/mnt/sdcard2/"
				+ SDCARD_UPDATE_PACKAGE_NAME);

		context.startService(updateIntent);
	}

	/**
	 * 检查卡刷包是否存在
	 * 
	 * @return
	 */
	public static boolean isSDUpdatePackageExist() {
		File file = new File("/mnt/sdcard2", SDCARD_UPDATE_PACKAGE_NAME);
		return file.exists() && file.length() > 0;
	}
}
